/** sps_uid_req.cpp - implemention of getting usbkey id request
 */


#include "sps_config.h"

#define SJN_DEVICE_ID             "deviceId"
#define SJN_PUBLIC_CERT           "publicCert"

SpsUidReq::SpsUidReq(const std::string& ip, const std::string& mac)
  : SpsReq(ip, mac)
  , devid_("")
  , pubcert_("")
{
}

SpsUidReq::~SpsUidReq()
{
}

std::string SpsUidReq::getResponse()
{
  if (err_ != ESPS_SUCCESS) {
    return SpsReq::getResponse();
  }
  
  json v;

  v[SJN_TYPE] = 1;
  v[SJN_CODE] = code_;
  v[SJN_RESULT_STATUS_CODE] = getResultStatusCode();
  v[SJN_RESULT_CODE] = getResultCode();
  v[SJN_RESULT_DESC] = getResultDesc();
  v[SJN_SESSION_ID] = session_;
  v[SJN_AGENT_CLIENT_IP] = local_ip_;
  v[SJN_ALGORITHM] = msgalgo_;

  json d;
  d[SJN_DEVICE_ID] = devid_;
  d[SJN_PUBLIC_CERT] = Base64Encode(pubcert_);
  
  v[SJN_RESULT_DATA] = d;
  
  v[SJN_SIGNATURE] = generateVerify(v);

  return v.to_string();
}


/*******************************************************************************
 * Protected functions                                                         *
 ******************************************************************************/

int SpsUidReq::doit()
{
  /*
   * TODO: Get usbkey id and public cert and set id to variable
   *       *devid_* and public cert to *pubcert_*.
   */
  
  return ESPS_SUCCESS;
}

std::string SpsUidReq::generateVerify(const json& v)
{
  std::list<std::string> l;

  l.push_back(v[SJN_TYPE].as_string());
  l.push_back(v[SJN_CODE].as_string());
  l.push_back(v[SJN_RESULT_STATUS_CODE].as_string());
  l.push_back(v[SJN_RESULT_CODE].as_string());
  l.push_back(v[SJN_RESULT_DESC].as_string());
  l.push_back(v[SJN_SESSION_ID].as_string());
  l.push_back(v[SJN_AGENT_CLIENT_IP].as_string());
  l.push_back(v[SJN_ALGORITHM].as_string());

  json d = v[SJN_RESULT_DATA];
  l.push_back(d[SJN_DEVICE_ID].as_string());
  l.push_back(d[SJN_PUBLIC_CERT].as_string());

  l.push_back(sps_priv_key);

  l.sort();

  std::string msg;
  std::list<std::string>::const_iterator i;
  for (i = l.begin(); i != l.end(); i++) {
    msg += (*i + "&");
  }

  msg.erase(msg.end() - 1);

  return getHash(msg);
}
